from rest_framework import serializers
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from .models import User, Address
from celery_tasks.email.tasks import send_verify_email


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        # 读取登录用户
        user = self.context['request'].user
        # 将登录用户重新的添加到校验之后的validated_data里面，方便后面赋值
        validated_data['user'] = user

        # 新增一条记录
        address = Address.objects.create(**validated_data)

        # 响应新增结果
        return address


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class EmailSerializer(serializers.ModelSerializer):
    """添加、更新邮箱序列化器"""

    class Meta:
        model = User
        fields = ['id', 'email']
        # 给email字段执行必传
        extra_kwargs = {
            'email': {
                'required':True
            }
        }

    def update(self, instance, validated_data):
        """
        更新邮箱:重写跟新数据的方法
        因为保存完了数据之后需要发送邮件
        而源代码中UpdateAPIView和EmailView中没有地址去发送邮件
        :param instance: 表示本次要跟新的模型对象，user
        :param validated_data: 经过验证的输入的数据
        :return: user
        """
        # user.email = validated_data.get('email')
        instance.email = validated_data.get('email')
        instance.save()

        # 生成邮箱激活链接
        # verify_url = http://www.meiduo.site:8080/success_verify_email.html?token=HASBDSHJKDBJHDB
        verify_url = instance.generate_email_verify_url()

        # 在更新了邮件之后，响应结果之前，发送邮箱的验证邮件(异步)
        send_verify_email.delay(instance.email, verify_url)

        return instance


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详细信息序列化器"""
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserSerializer(serializers.ModelSerializer):
    """注册序列化器"""

    # 补充模型类以外的映射字段
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    # 增加token字段
    token = serializers.CharField(label='登录状态token', read_only=True)

    class Meta:
        model = User
        # 输入字段：username, mobile, password, password2, allow, sms_code
        # 输出字段：id, username, mobile, token
        fields = ['id', 'username', 'mobile', 'password', 'password2', 'allow', 'sms_code', 'token']

        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 追加验证字段
    def validate_mobile(self, value):
        """
        验证手机号格式
        :param value: mobile
        :return: value
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """
        验证是哦福统一协议
        :param value: allow
        :return: value
        """
        if value != 'true':
            raise serializers.ValidationError('请勾选用户协议')
        return value

    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):
        """
        重写新增数据的方法:因为如果不重写会默认的保存write_only类型的字段到User,但是password2,allow,sms_code不能存
        :param validated_data: 经过校验的字段
        :return: None
        """
        # 移除不能存入到User的三个字段
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

        # 保存用户注册数据
        # User() save()
        # User.objects.create_user()
        # **validated_data : 将字典解包
        # 补充：*[] : 将列表或者集合解包
        user = User.objects.create(**validated_data)

        # 密码加密
        user.set_password(validated_data.get('password'))
        user.save() # ORM的save()

        # 在注册成成功之后，响应注册结果之前，生成JWT token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 使用注册后的user信息，生成载荷
        payload = jwt_payload_handler(user)
        # 使用载荷生成JWT token
        token = jwt_encode_handler(payload)

        # 给user对象动态的增加一个token属性，用于响应JWT token
        user.token = token

        # 响应注册结果
        return user








